var cim_avatar = "/static/im/images/user.png";
var cim_socket;

// 初始化PC端 LayIm组件 START
function initLayIm(ctxPath, userId, ip, port, username, password, name) {
    if (typeof(WebSocket) == "undefined") {
        console.info("不支持websocket");
        return;
    }
    cim_avatar = ctxPath + "/static/im/images/user.png";
    layui.use('layim', function (layim) {
        //init
        layim.on('ready', function (res) {
            var cim_lm = layui.layim;
            //显示在线人
            //建立WebSocket通讯
            createWebSocket(ctxPath, layim, userId, ip, port, username, password, cim_lm);
        });

        //基础配置
        layim.config({
            title: '我的通讯',
            init: {
                url: ctxPath + '/layim/pc/getImUser', //接口地址（返回的数据格式见layim文档）
                type: 'get', //默认get，一般可不填
                data: {
                    'userId': userId
                } //额外参数
            }, //获取主面板列表信息，下文会做进一步介绍

            //获取群员接口（返回的数据格式见下文）
            members: {
                url: '', //接口地址（返回的数据格式见下文）
                type: 'get', //默认get，一般可不填
                data: {} //额外参数
            },

            //上传图片接口（返回的数据格式见下文），若不开启图片上传，剔除该项即可
            uploadImage: {
                url: ctxPath + '/ajax/layim/uploadImg?number=' + username, //接口地址
                type: 'post' //默认post
            },

            //上传文件接口（返回的数据格式见下文），若不开启文件上传，剔除该项即可
            uploadFile: {
                url: ctxPath + '/ajax/layim/uploadFile?number=' + username,  //接口地址
                type: 'post' //默认post
            },

            isVideo: false, //开启聊天工具栏视频
            msgbox: layui.cache.dir + 'css/modules/layim/html/msgbox.html', //消息盒子页面地址，若不开启，剔除该项即可
            find: layui.cache.dir + 'css/modules/layim/html/find.html', //发现页面地址，若不开启，剔除该项即可
            chatLog: ctxPath + '/layim/pc/historymessage', //聊天记录页面地址，若不开启，剔除该项即可
            //可同时配置多个
            tool: [{
                alias: 'video', //工具别名
                title: '发送网络视频', //工具名称
                icon: '&#xe6ed;' //图标字体的class类名
            }]
        });

        layim.on('tool(video)', function (insert, send, obj) { //事件中的tool为固定字符，而code则为过滤器，对应的是工具别名（alias）
            layer.prompt({
                title: '插入代码',
                formType: 2,
                shade: 0
            }, function (text, index) {
                layer.close(index);
                insert('[pre class=layui-code]' + text + '[/pre]'); //将内容插入到编辑器，主要由insert完成
                send(); //自动发送
            });
            console.log(this); //获取当前工具的DOM对象
            console.log(obj); //获得当前会话窗口的DOM对象、基础信息
        });

        //监听在线状态切换
        layim.on('online', function (status) {
            console.log(status); //获得online或者hide
            //ajax 该表数据库中的状态
            //url: 请求地址, data: 请求数据{}, success: 请求成功的回调方法, async: 是否异步请求，默认true, pleaseWait: 是否显示请等待提示，默认true
            $.cajax(ctxPath + '/ajax/layim/changeImUserStatus', {
                userId: userId,
                status: status
            }, function (r) {
                layim.setFriendStatus(userId, status);
            });
        });

        layim.on('sign', function (value) {
            console.log(value); //获得新的签名
            //此时，你就可以通过Ajax将新的签名同步到数据库中了。
            $.cajax(ctxPath + '/ajax/layim/changeImUserSign', {
                userId: userId,
                value: value
            }, function (r) {
            });
        });

        //监听发送消息
        layim.on('sendMessage', function (data) {
            var To = data.to;
            var my = data.mine;
            var content = my.content;
            var msgType = 0;
            console.log("发送data：" + data);
            console.log("发送内容" + content)
            //根据发送内容区分类别0文字，1图片，2视频，3文件
            if (content.indexOf("img[") != -1) {
                content = content.replace("img[", "");
                content = content.substring(0, content.length - 1);
                msgType = 1;
            }
            if (content.indexOf("file(") != -1) {
                content = content.replace("file(", "").replace(")[下载文件]", "");
                if (content.indexOf(".mp4") != -1) {
                    msgType = "2";
                    my.content = "video[" + content + "]";
                } else {
                    msgType = "3";
                }
            }
            //TODO JIM群主说会扩展结果 暂时只能这样存 07/20
            var message = content + '%' + name;
            var receiveId = To.id;
            if (!username) {
                return
            }
            if ($.trim(message) == '') {
                layer.msg("请输入要发送的消息!");
                return;
            }
            if (!window.WebSocket) {
                //判断是发送好友消息还是群消息
                if (To.type == "friend") {//发送给朋友
                    var extras = {
                        'name': name
                    }
                    var addExtras = "name," + JSON.stringify(extras); //将JSON对象转化为JSON字符
                    var createTime = new Date().getTime();
                    var msg = "{\"from\": \"" + userId + "\",\"to\": \"" + receiveId + "\",\"cmd\":11,\"createTime\":" + createTime + ",\"chatType\":\"2\",\"msgType\": \"" + msgType + "\",\"content\": \"" + message + "\",\"extras\": \"" + addExtras + "\"}";
                    cim_socket.send(msg);
                } else {//发送群组
                    var extras = {
                        name: To.groupname
                    }
                    var msg = "{\"from\": \"" + userId + "\",\"createTime\":" + createTime + ",\"cmd\":11,\"group_id\": \"" + receiveId + "\",\"chatType\":\"1\",\"msgType\":\"" + msgType + "\",\"content\": \"" + message + "\"}";
                    cim_socket.send(msg);
                }
                return;
            } else {
                if (cim_socket.readyState == WebSocket.OPEN) {
                    //判断是发送好友消息还是群消息
                    if (To.type == "friend") {
                        var extras = name;
                        var addExtras = "name," + JSON.stringify(extras); //将JSON对象转化为JSON字符
                        var createTime = new Date().getTime();

                        var msg = "{\"from\": \"" + userId + "\",\"to\": \"" + receiveId + "\",\"cmd\":11,\"createTime\":" + createTime + ",\"chatType\":\"2\",\"msgType\": \"" + msgType + "\",\"content\": \"" + message + "\",\"name\": \"" + name + "\"}";
                        cim_socket.send(msg);
                    } else {
                        var extras = {
                            name: To.groupname
                        }
                        var createTime = new Date().getTime();
                        var msg = "{\"from\": \"" + userId + "\",\"createTime\":" + createTime + ",\"cmd\":11,\"group_id\": \"" + receiveId + "\",\"chatType\":\"1\",\"msgType\":\"" + msgType + "\",\"content\": \"" + message + "\"}";
                        cim_socket.send(msg);
                    }
                }
            }
        });
    });
}

//初始化PC端 LayIm组件 END
/**
 * 公共的 创建WebSocket连接
 * @param layim
 */
function createWebSocket(ctxPath, layim, userId, ip, port, username, password, cim_lm) {

    // socket创建对象
    try {
        cim_socket = new WebSocket("ws://" + ip + ":" + port + "?username=" + username + "&password=" + password);
    } catch (e) {
        $.alert(e.message);
    }
    // 和服务器建立连接,发送登陆Jim命令
    cim_socket.onopen = function (e) {
        var userCmd = "{\"cmd\":17,\"type\":\"0\",\"userid\":\"" + userId + "\"}";
        var msgCmd = "{\"cmd\":19,\"type\":\"0\",\"userId\":\"" + userId + "\"}";
        cim_socket.send(userCmd);//获取登录用户信息;
        cim_socket.send(msgCmd);//获取用户离线消息(好友+群组);
    };
    //连接失败
    cim_socket.onerror = function (e) {
        $.alert('即时通讯链接失败');
    };
    //关闭连接退出登陆
    cim_socket.onclose = function (e) {
        console.log("关机聊天")
    };
    //监听服务器的信息
    cim_socket.onmessage = function (e) {
        var data = e.data;
        var dataObj = eval("(" + data + ")");//转换为json对象
        //console.log("监听数据内容"+JSON.stringify(dataObj))
        if (dataObj.command == 11) {//接收到聊天响应处理;
            COMMAND_CHAT_RESP(dataObj, cim_lm);
        } else if (dataObj.command == 18) {//获取用户信息响应处理;
            COMMAND_GET_USER_RESP(dataObj, layim);
        } else if (10000 == dataObj.code && dataObj.command == 12) {//聊天发送状态;
            COMMAND_CHAT_RESP_SEND_STATUS(data);
        } else if (dataObj.command == 9) {//加入群组的消息通知处理;
            COMMAND_JOIN_GROUP_NOTIFY_RESP(ctxPath, dataObj, cim_lm);
        } else if (dataObj.command == 10) {
            COMMAND_EXIT_GROUP_NOTIFY_RESP(ctxPath, dataObj, cim_lm);//退出聊天室
        } else if (dataObj.command == 20 && dataObj.code == 10016) {//处理离线消息;
            var msgFlag = "离线消息";
            COMMAND_GET_MESSAGE_RESP(dataObj, msgFlag);
        } else if (dataObj.command == 20 && dataObj.code == 10018) {//处理历史消息;
            var msgFlag = "历史消息";
            var msgObj = dataObj.data;
            if (msgObj) {
                COMMAND_GET_MESSAGE_RESP(dataObj, msgFlag);//处理用户同步+持久化消息
            } else {//没有历史消息;
                // OTHER(data);
            }
        } else {
            //OTHER(data);
        }
        //  scrollToBottom();
    };
    return cim_socket;
}

//接收到聊天响应处理;
function COMMAND_CHAT_RESP(data, cim_lm) {
    console.log("监听新消息-----" + JSON.stringify(data))
    var chatObj = data.data;
    var createTime = chatObj.createTime;
    var receiveId = chatObj.from;
    var receiveName = chatObj.content.split('%')[1];

    var content = chatObj.content.split('%')[0];
    var group_id = chatObj.group_id;
    var msgType = chatObj.msgType;
    //消息类型0 文字 1 图片 2 视频 3文件
    if ("1" == msgType) {
        content = "img[" + content + "]";
    }
    if ("3" == msgType) {
        content = "file(" + content + ")[下载文件]";
    }
    if ("2" == msgType) {
        content = "video[" + content + "]";
    }
    if (group_id) {//群聊
        var mine = false //是否我发送的消息，如果为true，则会显示在右方
        if (receiveName == name) {
            mine = true //是否我发送的消息，如果为true，则会显示在右方
            return;
        }

        cim_lm.getMessage({
            username: receiveName,
            avatar: cim_avatar + "?" + new Date().getTime(),
            id: group_id,
            type: "group",
            content: content,
            mine: mine,
            timestamp: createTime
        });

    } else {//私聊
        var fromId = chatObj.id;
        cim_lm.getMessage({
            username: receiveName,
            avatar: cim_avatar + "?" + new Date().getTime(),
            id: receiveId,
            type: "friend",
            content: content,
            fromid: fromId,
            timestamp: createTime
        });
    }
}

function COMMAND_GET_USER_RESP(data, layim) {
    var user = data.data;
}

function COMMAND_CHAT_RESP_SEND_STATUS() {
    console.log('发送--------------[]')
}

//加入群组的消息通知处理;
function COMMAND_JOIN_GROUP_NOTIFY_RESP(ctxPath, data, cim_lm) {
    var joinUser = data.data.user;
    console.log(JSON.stringify(joinUser));
    $.cajax(ctxPath + '/api/app/login/online', {
        userId: joinUser.id,
    }, function (r) {
        cim_lm.setFriendStatus(joinUser.id, 'online');
    }, true, false);
}

//退出聊天室
function COMMAND_EXIT_GROUP_NOTIFY_RESP(ctxPath, data, cim_lm) {
    var outUset = data.data.user;
    $.cajax(ctxPath + '/api/app/login/offline', {
        userId: outUset.id,
    }, function (r) {
        cim_lm.setFriendStatus(outUset.id, 'offline');
    }, true, false);
}

//处理用户同步+持久化消息
function COMMAND_GET_MESSAGE_RESP(data, msgFlag) {
    console.info(data);
}